﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZQNB.BaseLib.Core.Models;
using ZQNB.Common.Encrypt;
using ZQNB.Common.FileDbs;

namespace ZQNB.BaseLib.Core.Services
{
    public class CloudAccountService : ICloudAccountService
    {
        private readonly IFileDbHelper _fileDbHelper;
        private readonly PasswordEncryptor _passwordEncryptor;

        public CloudAccountService(IFileDbHelper fileDbHelper, PasswordEncryptor passwordEncryptor)
        {
            _fileDbHelper = fileDbHelper;
            _passwordEncryptor = passwordEncryptor;
        }

        public void Init(string userName, string password, bool passwordAlreadyEncrypted = false)
        {
            var theOnes = _fileDbHelper.Read<CloudAccount>();
            var theOne = theOnes.SingleOrDefault(x => x.Username == userName);
            if (theOne == null)
            {
                theOne = new CloudAccount();
                theOnes.Add(theOne);
            }

            theOne.Username = userName;
            theOne.Password = passwordAlreadyEncrypted ? password : _passwordEncryptor.Encrypt(password, PasswordFormat.Hashed);
            
            _fileDbHelper.Save(theOnes);
        }

        public bool Validate(string identityName, string password)
        {
            var theOnes = _fileDbHelper.Read<CloudAccount>();
            var theOne = theOnes.SingleOrDefault(x => x.Username == identityName);
            if (theOne == null)
            {
                return false;
            }

            return theOne.Password == _passwordEncryptor.Encrypt(password, PasswordFormat.Hashed);
        }

        public bool ChangePassword(string identityName, string oldPass, string newPass)
        {
            var theOnes = _fileDbHelper.Read<CloudAccount>();
            var theOne = theOnes.SingleOrDefault(x => x.Username == identityName);
            if (theOne == null)
            {
                return false;
            }

            bool isOk = theOne.Password == _passwordEncryptor.Encrypt(oldPass, PasswordFormat.Hashed);
            if (!isOk)
            {
                return false;
            }

            theOne.Password = _passwordEncryptor.Encrypt(newPass, PasswordFormat.Hashed);
            return true;
        }

        public void Remove(string userName)
        {
            var theOnes = _fileDbHelper.Read<CloudAccount>();
            var theOne = theOnes.SingleOrDefault(x => x.Username == userName);
            if (theOne == null)
            {
                return;
            }

            theOnes.Remove(theOne);
            _fileDbHelper.Save(theOnes);
        }
    }
}
